package com.keldian.mobilesafe.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.keldian.mobilesafe.R;
import com.keldian.mobilesafe.activity.SendRocketActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 15-12-30.
 */
public class FloatWindowService extends Service implements View.OnTouchListener, View.OnClickListener {
    private Timer timer;
    private RelativeLayout mFloatLayout;
    private RelativeLayout mFunLayout;


    private WindowManager.LayoutParams layoutParams;
    private WindowManager mWindowManager;
    //小火箭的图标
    private ImageView iv;
    private ImageView iv_bottom;
    private ImageView iv_top;
    private AnimationDrawable rocketAnimation;
    private RelativeLayout rl_sendRocket;
    private WindowManager.LayoutParams rocket_layoutParams;

    private static final int ADD_HOME_FLAG = 1;
    private static final int REMOVE_HOME_FLAG = 3;
    private static final int ADD_DIALOG_FLAG = 2;

    private int flag = 0;
    private TextView homeMemory;
    private float mTouchStartY;
    private float mTouchStartX;

    private float mRocketTouchStartY;
    private float mRocketTouchStartX;

    private int Screen_Width;
    private ImageView homeImg;

    private float ScrenWidth;
    private float ScrenHeight;
    private long mStartTouchTime = 0;
    private long mEndTouchTime = 0;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        rl_sendRocket = (RelativeLayout) LayoutInflater.from(this).
                inflate(R.layout.send_rocket, null);

        iv = (ImageView) rl_sendRocket.findViewById(R.id.iv);


        iv.setBackgroundResource(R.drawable.rocket);
        iv_top = (ImageView) rl_sendRocket.findViewById(R.id.iv_top);
        iv_bottom = (ImageView) rl_sendRocket.findViewById(R.id.iv_bottom);
        rocketAnimation = (AnimationDrawable) iv.getBackground();
        rocketAnimation.start();

        mWindowManager = (WindowManager) getApplication().getSystemService
                (getApplication().WINDOW_SERVICE);

        DisplayMetrics metrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(metrics);

        int sc_width = metrics.widthPixels;
        int sc_height = metrics.heightPixels;

        Log.i("TAG", sc_height + "");

        ScrenWidth = sc_width;
        ScrenHeight = sc_height;


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new RefreshTask(), 0, 1000);
        }
        return super.onStartCommand(intent, flags, startId);
    }


    //TODO
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        float y = event.getRawY();
        float x = event.getRawX();

        mRocketTouchStartX = x;
        mRocketTouchStartY = y;

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mStartTouchTime = System.currentTimeMillis();
                mTouchStartY = event.getY();
                mTouchStartX = event.getX();
                Intent intent = new Intent(this, SendRocketActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d("FloatWindowService", "ACTION_MOVE");
                //当拖动时，移除原先的现实动画，显示小火箭发射布局，替换为小火箭
//                addSmallRokect();
//                CreateFunctionView();
                updateViewPosition(x, y);
                break;
            case MotionEvent.ACTION_UP:
                mEndTouchTime = System.currentTimeMillis();

                updateViewPosition2(x, y);
                //释放后如果不在发射位置 则移除小火箭，替换为原来的现实动画
                mTouchStartY = 0.0f;
                mTouchStartX = 0.0f;
                break;
            default:
                break;
        }
//
        return mEndTouchTime - mStartTouchTime > 1000;
    }

    //显示小火箭图标
    private void addSmallRokect() {
        initRocketView();
        createFloatRokectView();

    }

    private void initRocketView() {
    }

    //TODO
    private void createFloatRokectView() {
        if (rl_sendRocket != null) {
            return;
        }
        rocket_layoutParams = new WindowManager.LayoutParams();

        rocket_layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        rocket_layoutParams.format = PixelFormat.RGBA_8888;

        rocket_layoutParams.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        rocket_layoutParams.gravity = Gravity.TOP | Gravity.LEFT;

        DisplayMetrics metrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(metrics);

        int sc_width = metrics.widthPixels;
        int sc_height = metrics.heightPixels;

        Log.i("TAG", sc_height + "");

        ScrenWidth = sc_width;
        ScrenHeight = sc_height;

        rocket_layoutParams.x = 700;
        rocket_layoutParams.y = sc_height / 2;

        rocket_layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        rocket_layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        mWindowManager.addView(rl_sendRocket, rocket_layoutParams);

        //TODO
        //实现小火箭的移动触摸事件

    }

    private void updateViewPosition(float x, float y) {
        layoutParams.x = (int) (x - mTouchStartX);
        layoutParams.y = (int) (y - mTouchStartY);
        mWindowManager.updateViewLayout(mFloatLayout, layoutParams);
    }

    private void updateViewPosition2(float x, float y) {
//        layoutParams.x = (int) (x - mTouchStartX);
//        layoutParams.y = (int) (y - mTouchStartY);
//        Log.i("TAG", x+"");
//        Log.i("TAG", ScreenWidth / 2+"----");

        if (x >= ScrenWidth / 2) {
            layoutParams.x = (int) (ScrenWidth);
            mWindowManager.updateViewLayout(mFloatLayout, layoutParams);
        } else {
            layoutParams.x = 0;
            mWindowManager.updateViewLayout(mFloatLayout, layoutParams);
        }
    }


    @Override
    public void onClick(View v) {
        Toast.makeText(this, "Clickme!", Toast.LENGTH_SHORT).show();
    }

    private void CreateFunctionView() {
        RemoveFloatView();
        flag = ADD_DIALOG_FLAG;

        layoutParams.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        LayoutInflater inflater = LayoutInflater.from(getApplication());

        repositionRocket();
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        layoutParams.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;

        mFunLayout = (RelativeLayout) inflater.inflate(R.layout.fullwindow, null);

        mWindowManager.addView(rl_sendRocket, layoutParams);
        iv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                float y = event.getRawY() - 38;
                float x = event.getRawX();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mStartTouchTime = System.currentTimeMillis();
                        mTouchStartY = event.getY();
                        mTouchStartX = event.getX();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        updateViewPosition(x, y);
                        break;
                    case MotionEvent.ACTION_UP:
                        mEndTouchTime = System.currentTimeMillis();
                        updateViewPosition(x, y);
                        mTouchStartY = 0.0f;
                        mTouchStartX = 0.0f;
                        break;
                    default:
                        break;
                }
//
                return mEndTouchTime - mStartTouchTime > 1000;
            }
        });
    }

    //TODO
    private Handler handler2 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(FloatWindowService.this,
                    ScrenWidth / 2 + "--" + ScrenHeight / 2, Toast.LENGTH_SHORT).show();
            iv.setX(ScrenWidth / 2);
            iv.setY(ScrenHeight / 2);
        }

    };

    private void repositionRocket() {
        new Thread() {
            public void run() {
                handler2.sendEmptyMessage(0);
            }
        }.start();
    }


    private void RemoveFunctionView() {
        if (mWindowManager != null) {
            mWindowManager.removeView(mFunLayout);
            mFunLayout = null;
        }
    }

    class RefreshTask extends TimerTask {
        @Override
        public void run() {
            if (flag == ADD_DIALOG_FLAG) {
                return;
            }
            switch (isHome()) {
                case ADD_HOME_FLAG:
                    handler.sendEmptyMessage(ADD_HOME_FLAG);
                    break;
                case REMOVE_HOME_FLAG:
                    handler.sendEmptyMessage(REMOVE_HOME_FLAG);
                    break;
            }
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ADD_HOME_FLAG:
                    createFloatView();
                    break;
                case REMOVE_HOME_FLAG:
                    RemoveFloatView();
                    break;
                default:
                    break;
            }
        }

    };

    private void RemoveFloatView() {
        if (mFloatLayout != null) {
            mWindowManager.removeView(mFloatLayout);
            mFloatLayout = null;
        }

    }

    private void createFloatView() {
        if (mFloatLayout != null) {
            return;
        }
        layoutParams = new WindowManager.LayoutParams();

        layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        layoutParams.format = PixelFormat.RGBA_8888;

        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;

        DisplayMetrics metrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(metrics);

        int sc_width = metrics.widthPixels;
        int sc_height = metrics.heightPixels;

        ScrenWidth = sc_width;

        layoutParams.x = 700;
        layoutParams.y = sc_height / 2;

        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        LayoutInflater inflater = LayoutInflater.from(getApplication());

        mFloatLayout = (RelativeLayout) inflater.inflate(R.layout.demo, null);


        mWindowManager.addView(mFloatLayout, layoutParams);
        mFloatLayout.setOnTouchListener(this);

        homeImg = (ImageView) mFloatLayout.findViewById(R.id.homeImg);
        homeMemory = (TextView) mFloatLayout.findViewById(R.id.homeMemory);

        mFloatLayout.setOnClickListener(this);
    }

    private int isHome() {
        ActivityManager activityManager = (ActivityManager) getSystemService
                (Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> rti = activityManager.getRunningTasks(1);
        if (getHomes().contains(rti.get(0).topActivity.getPackageName())) {
            return flag = ADD_HOME_FLAG;
        } else {
            return flag = REMOVE_HOME_FLAG;
        }
    }


    private List<String> getHomes() {
        List<String> names = new ArrayList<String>();
        PackageManager packageManager = this.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> resolveList = packageManager.queryIntentActivities
                (intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo ri : resolveList) {
            names.add(ri.activityInfo.packageName);
        }
        return names;
    }

    @Override
    public void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }
}
